
let { HttpRequest, globalData, cloud, mfutil, URLChangeCommon, UserAccess, addUserStat } = getApp()
import cssObj from './css'
console.log('=======================', cssObj)
const params = {}
Component({
  mixins: [],
  data: {
    parr: [],
    dataArray: {},
    tilesDetail: [],
    userPionts: null,
    nodes: [],
    newNodes: [],
    titleNodes: [],
    mobile_txet: [],
    dataNum: {},
    state: false,
    show: true,
    playFunc: null,
    pauseFunc: null,
    endedFunc: null,
    time: 0,
    change: 0,
    flag: false,
    activetype: null,
    accomplishActive: false,
    state: false,
    newState: null,
    scrolly: false,
    time2: "",
    ShowText: false,
    // 抽奖
    prize_arr: [
      { id: '1', type: 'prize', name: '奖品1', isSelected: false },
      { id: '2', type: 'prize', name: '奖品2', isSelected: false },
      { id: '3', type: 'prize', name: '奖品3', isSelected: false },
      { id: '4', type: 'prize', name: '奖品8', isSelected: false },
      { id: '5', type: 'prize', name: '奖品9', isSelected: false },
      { id: '6', type: 'prize', name: '奖品4', isSelected: false },
      { id: '7', type: 'prize', name: '奖品7', isSelected: false },
      { id: '8', type: 'prize', name: '奖品6', isSelected: false },
      { id: '9', type: 'prize', name: '奖品5', isSelected: false },
    ],
    // 抽奖状态，是否转完了
    isTurnOver: true
  },
  props: {
    json: null,
    data: null,
    islucky: null,
    activetype: null,
    newState: null
  },
  didMount() {
    let { parr, itme } = this.data
    this.data.dataArray = this.props.json
    this.data.dataNum = this.props.dataNum
    this.data.activetype = this.props.activetype
    this.data.userPionts = globalData.userInfo.availablePoint;
    this.data.islucky = !!this.props.islucky
    console.log(this.props.islucky, 'isluckyisluckyisluckyislucky')
    // 判断开奖时间

    // let time = this.data.dataArray.end_time ? this.data.dataArray.end_time.replace('-', '年').replace('-', '月').replace(' ', '日') : '';
    let time = this.data.dataArray.end_time ? this.data.dataArray.end_time.replace(/[/-]/, '年').replace(/[/-]/, '月').replace(' ', '日') : '';
    this.setData({
      // time: time,
      time2: time
    })
    this.videoContext = my.createVideoContext('video' + this.data.dataArray.id);
    this.setData({
      item: this.data.dataArray
    })
    // this.data.dataNum = this.props.datathis.data.dataArray
    if (this.data.dataArray.mobile_intro_rich || this.data.dataArray.mobile_title_rich || this.data.dataArray.mobile_complete_text_rich || this.data.dataArray.prize_items) {
      let nodes = this.data.dataArray.mobile_intro_rich
      let titnodes = this.data.dataArray.mobile_title_rich
      let mobile_complete_text_rich = this.data.dataArray.mobile_complete_text_rich
      let prize = this.data.dataArray
      console.log(prize, "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[");
      this.setData({
        parr:prize
      })
      // prize.map((value, index) => {
      //   parr.push(value)
      // })
      console.log(parr, "prize((((((((((((((((((((((((((((");
      // if (nodes || titnodes || mobile_complete_text_rich) {
      let a = this.fn(nodes)
      let b = this.fnTitle(titnodes)
      console.log("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", b)
      if (mobile_complete_text_rich) {
        let c = this.fn(mobile_complete_text_rich)
        this.setData({
          newNodes: a,
          titleNodes: b,

          mobile_txet: c
        })
      } else {
        this.setData({
          newNodes: a,
          titleNodes: b,

        })
      }

    }
  },
  didUpdate() {

    if (this.props.successActives == true || this.props.sucessTile == true) {
      this.data.scrolly = true
    } else {
      this.data.scrolly = false
    }
  },
  didUnmount() { },
  methods: {
    // 视频
    onVideoPlay(func) {
      this.setData({
        playFunc: func
      })
    },
    _hide() {
      this.videoContext.pause();
    },
    play() {
      this.videoContext.play();

    },
    pause() {
      this.videoContext.pause();
    },
    stop() {
      this.videoContext.stop();
    },
    onPlay() {
      // this.data.state = truess
      // debugger
      console.log('视频开始播放99999999999999999999999999')
      this.timeChange()
      try {
        this.data.playFunc()
      } catch (e) {

      }
    },
    onPlayError(event) {
      mfutil.launchErrPage(53001)
    },
    timeChange() {
      let { time } = this.data;
      let myTime = setInterval(() => {
        this.setData({
          time: ++time
        })
      }, 1000)
      this.setData({
        myTime
      })
    },
    onPause() {
      let { myTime } = this.data;
      clearInterval(myTime)
      try {
        this.data.pauseFunc()
      } catch (e) {

      }
    },
    onEnded() {
      clearInterval(this.data.myTime)
      // 视频播放结束 判断是否做过任务  如果是则不弹出弹窗
      // console.log(this.data.dataArray.limit, this.data.dataNum.todo);
      if (this.data.dataNum.todo > 0 || this.data.dataArray.limit == 0) {
        try {
          this.setData({
            successActives: true
          })
          console.log('视频观看结束')
          this.data.endedFunc()
        } catch (e) {

        }
      }

    },
    async accomplish() {
      let { item, time, accomplishActive, myTime } = this.data;
      clearInterval(myTime)
      if (time >= item.required_duration && !accomplishActive && this.data.activetype != 'finished') {
        let datetime = new Date(+new Date() + 8 * 3600 * 1000).toJSON().substr(0, 19).replace("T", " ").replace(/\-/g, "/");
        let bodyObj1 = {
          do_datetime: datetime,
          duration: time
        }
        let parmasObj1 = {
          member_id_type: 1,
          member_id: globalData.userInfo.memberId
        }
        let path1 = `/vans-family/api/v2.1/project/vansFamily/cms/forward/post?url=/v1/cms/api/tile/${item.type}/${item.id}/done`;
        let res = await HttpRequest(path1, 'POST', parmasObj1, bodyObj1);
        if (res.data.code == 0) {
          my.showToast({
            type: 'success',
            content: '完成视频观看任务啦！',
            duration: 2000,
          });
          this.setData({
            accomplishActive: true
          })
          clearInterval(myTime)
        } else if (res.data.code == 53012 || res.data.code == 53014 || res.data.code == 53001) {
          console.log("13123");

          // my.alert({
          //   content: res.data.msg
          // })
        } else {
          mfutil.launchErrPage(53001)
        }
      }

      // 自定义埋点
      let customAccessoptions = {
        customType: 'TileDone_' + this.data.dataArray.id + '_视频观看完成TileDone',
        // tileId: this.data.dataArray.id,
        // points: this.data.dataArray.points
      }
      let tracks = addUserStat(customAccessoptions)
      console.log(id, 'TileDone');
    },
    onTimeUpdate() {
      let { item, time, accomplishActive, flag } = this.data;

      console.log(!flag, '---', time >= item.required_duration, '---', !accomplishActive, '---', this.data.activetype);
      if (!flag && time >= item.required_duration && !accomplishActive && this.data.activetype != 'finished') {
        console.log(333333333333333333333333333, this.data);
        // tile限制次数，并且用户未完成过，或者不限制次数调用tiledone接口
        // if ((this.data.json.related.done < 1 && this.data.dataArray.limit == 1) || this.data.dataArray.limit == 0 || this.data.dataArray.limit > 1) {
        if ((this.data.dataNum.done < 1 && this.data.dataArray.limit == 1) || this.data.dataArray.limit == 0 || this.data.dataArray.limit > 1) {
          console.log(44444444444444444444444);
          this.accomplish()
        }
        this.setData({
          flag: true
        })
      }
      // }
    },
    // 修改视频地址
    setSrc(_src) {
      const { item } = this.data;
      this.setData({
        item: { ...item, src: _src }
      })
    },
    urlChange(event) {
      console.log(this.data.dataArray);

      let { item } = event.currentTarget.dataset;
      console.log(item);

      URLChangeCommon(item)
      /**
* 用户行为记录埋点
*/
      let routerArr = getCurrentPages();
      let UserAccessoptions = {
        grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',
        name: routerArr[routerArr.length - 1].data.pagetitle,
        address: this.data.dataArray.id,
        String4: item.cta_button_name,
      }
      let track = UserAccess(UserAccessoptions)

      // 自定义埋点
      let customAccessoptions = {
        customType: 'TileCTA_' + this.data.dataArray.id + '_' + item.cta_button_name
        // tileId: this.data.dataArray.id,
        // ctabtn: item.cta_button_name
      }
      // debugger
      console.log(customAccessoptions.customType);

      let tracks = addUserStat(customAccessoptions)
    },
    saveRef(ref) {
      this.setData({
        state: ref.data.state
      })

    },
    cfn(item) {
      item.name = item.tag;
      delete item.tag;
      if (item.name == 'font') {
        item.name = 'span'
      }
      if (item.attrs) {
        let tempattrs = {
          style: ''
        }
        console.log('11111111111111111', item.attrs);

        item.attrs.map((v) => {

          if (v.name == 'style') {
            tempattrs['style'] += v.value
          } else if (v.name == 'color' || v.name == 'size' || v.name == 'line-height') {
            tempattrs['style'] += cssObj[v.name + v.value]
          } else {
            tempattrs[v.name] = v.value

          }
        });
        // console.log( '2222222222222222222',item.attrs);
        item.attrs = tempattrs
        // console.log(item.attrs);

      }
      if (item.children) {
        item.children = this.fn(item.children)
      }

      return item
    },

    fn(targetData) {
      console.log("xxxxxxxxxxxxxxxxxxxxx1", targetData)

      let newDate = targetData ? targetData.map(item => {
        return Object.prototype.toString.call(item) === "[object Object]" ? this.cfn(item) : { type: 'text', text: item }
      }) : [];
      return newDate

    },

    cfnTitle(item) {
      item.name = item.tag;
      delete item.tag;
      if (item.name == 'font') {
        item.name = 'span'
      }
      if (item.attrs) {
        let tempattrs = {
          style: ''
        }
        console.log('11111111111111111', item.attrs);

        item.attrs.map((v) => {

          if (v.name == 'style') {
            tempattrs['style'] += v.value
          } else if (v.name == 'color' || v.name == 'size' || v.name == 'line-height') {
            tempattrs['style'] += cssObj[v.name + v.value]
          } else {
            tempattrs[v.name] = v.value

          }
        });
        // console.log( '2222222222222222222',item.attrs);
        item.attrs = tempattrs
        // console.log(item.attrs);

      }
      if (item.children) {
        item.children = this.fnTitle(item.children)
      }

      return item
    },

    fnTitle(targetData) {
      console.log("--------------------------xxxxxxxxxxxxxxxxxxxxx1", targetData)

      let newDate = targetData ? targetData.map(item => {
        if (Object.prototype.toString.call(item) == "[object String]" && item.length) {
          console.log("///////////////////////////////////////////////////////", item)
          this.setData({ isHave: true })
        }
        return Object.prototype.toString.call(item) === "[object Object]" ? this.cfnTitle(item) : { type: 'text', text: item }
      }) : [];
      return newDate

    },
    newNodesTap(event) {
      my.navigateToMiniProgram({
        appId: event.target.dataset.id,
        success: (res) => {
          console.log(JSON.stringify(res))
        },
        fail: (res) => {
          console.log(JSON.stringify(res))
        }
      });

      /**
* 用户行为记录埋点
*/
      let routerArr = getCurrentPages();
      let UserAccessoptions = {
        grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',
        name: routerArr[routerArr.length - 1].data.pagetitle,
        address: this.data.dataArray.id,
        String4: this.data.dataArray.id + '-长图'
      }
      let track = UserAccess(UserAccessoptions)

      // 自定义埋点
      let customAccessoptions = {
        customType: this.data.dataArray.id + '-长图'
      }
      let tracks = addUserStat(customAccessoptions)
    },
    navigateToOutside(event) {
      console.log(this.data.dataArray);
      if (event.target.dataset.id) {
        let linkId = event.target.dataset.id.substring(0, 4);
        if (linkId == 'http') {
          console.log(event.target.dataset.id);

          my.call("navigateToOutside", {
            url: event.target.dataset.id
          })
        } else {
          console.log(event.target.dataset.id);

          my.redirectTo({ url: event.target.dataset.id })
        }

      }


      // my.call("navigateToOutside", {
      //   url: event.target.dataset.id
      // })

      /**
  * 用户行为记录埋点
  */
      let routerArr = getCurrentPages();
      let UserAccessoptions = {
        grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',
        name: routerArr[routerArr.length - 1].data.pagetitle,
        address: this.data.dataArray.id,
        String4: this.data.dataArray.id + '-长图'
      }
      let track = UserAccess(UserAccessoptions)


      // 自定义埋点
      let customAccessoptions = {
        customType: this.data.dataArray.id + '-长图'
      }
      let tracks = addUserStat(customAccessoptions)
    },

    // 优化页面滚动


    onScrollToUpper(event) {
      this.setData({
        scrolly: false,
        ScrollToUpper: true,
        ScrollToLower: false
      })

    },

    onScrollToLower() {
      this.setData({
        scrolly: false,
        ScrollToLower: true,
        ScrollToUpper: false
      })

    },
    onTouchStart(event) {

      console.log(event, 'onTouchStartonTouchStart')

      this.setData({

        starty: event.changedTouches[0].pageY,

      })

    },
    onTouchMove(event) {

      //当前pagey

      this.setData({

        movey: event.changedTouches[0].pageY

      })

      let { scrollTop } = this.data;

      let { ScrollToUpper, ScrollToLower, movey, starty } = this.data;

      if (ScrollToUpper && (starty > movey)) {

        this.setData({

          scrolly: true,

          ScrollToUpper: false,

          ScrollToLower: false

        })

      } else

        if (ScrollToUpper && (starty < movey)) {

          this.setData({

            scrolly: false,

          })

        }

      if (ScrollToLower && (starty < movey)) {

        this.setData({

          scrolly: true,

          ScrollToUpper: false,

          ScrollToLower: false

        })

      } else

        if (ScrollToLower && (starty > movey)) {

          this.setData({

            scrolly: false,

          })

        }

    },



  },
});